package ss

import (
	"errors"
	"reflect"
)

type M map[string]interface{}

func (s M) Len() int              { return len(s) }
func (s M) Swap(i, j string)      { s[i], s[j] = s[j], s[i] }
func (s M) Less(i, j string) bool { return i < j }
func (s *M) String() string       { data, _ := json.Marshal(s); return string(data) }

type Obj M
type Map M
type ArrayObj []Obj

type ArrayString []string
type ArrayInt []int
type ArrayInt64 []int64
type ArrayFloat []float64

func AssertObj(val interface{}) (Obj, error) {
	obj := Obj{}
	switch val.(type) {
	case map[string]interface{}:
		for s, i := range val.(map[string]interface{}) {
			obj[s] = i
		}
		return obj, nil
	case M:
		for s, i := range val.(M) {
			obj[s] = i
		}
		return obj, nil

	case Map:
		for s, i := range val.(Map) {
			obj[s] = i
		}
		return obj, nil
	case Obj:
		return val.(Obj), nil
	}

	return nil, errors.New("数据类型错误")
}

func AssertArrayObj(val interface{}) (ArrayObj, error) {
	array := ArrayObj{}
	tp := reflect.TypeOf(val)
	if tp.Kind() == reflect.Slice {
		vo := reflect.ValueOf(val)
		for i := 0; i < vo.Len(); i++ {
			fieldVal := vo.Index(i).Interface()
			obj, err := AssertObj(fieldVal)
			if err != nil {
				return nil, err
			}
			array = append(array, obj)
		}
		return array, nil
	}

	return nil, errors.New("数据类型错误")
}
